package com.example.finaltool.service;

import com.example.finaltool.annotations.Timer;
import com.example.finaltool.consts.Table;
import com.example.finaltool.mapper.SysCorpStationMapper;
import com.example.finaltool.model.DepInfo;
import com.example.finaltool.model.MyRuntimeException;
import com.example.finaltool.model.config.Data;
import com.example.finaltool.model.config.Zhudiwang;
import com.example.finaltool.utils.PrintUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysCorpStationService {

    SysCorpStationMapper mapper;

    @Autowired
    public SysCorpStationService(SysCorpStationMapper mapper) {
        this.mapper = mapper;
    }

    @Timer(Table.SYS_CORP_STATION)
    @Transactional(rollbackFor = Exception.class)
    public void save(Data data, DepInfo info) {
        String corpId = data.getCorpId();
        List<Long> exist = mapper.getSubIds(corpId);
        Map<String, Map<String, String>> map = data.getBianhaoAndId();
        info.getCunDepInfoList().forEach(i -> {
            if (exist.contains(i.getCunDepId())) {
                PrintUtils.showExist(Table.SYS_CORP_STATION, i.getCunName());
            } else {
                if (!map.containsKey(i.getCunName())) {
                    log.error("配置中村名称与钉钉中的名称不匹配：");
                    List<String> names = map.keySet().stream().filter(v -> v.contains(i.getCunName()) || i.getCunName().contains(v)).collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(names)) {
                        log.error("配置: " + map.keySet());
                    } else {
                        log.error("可能的配置: " + names);
                    }
                    log.error("钉钉: " + i.getCunName());
                    throw new MyRuntimeException("配置中村名称与钉钉中的名称不匹配");
                }
                mapper.save(corpId, map.get(i.getCunName()).get(Zhudiwang.KEY_BIANHAO), map.get(i.getCunName()).get(Zhudiwang.KEY_ID), i.getCunDepId());
            }
        });
    }
}
